//
//  CourseViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-10.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//
//  课程视图

#import "CourseViewController.h"
#import "CourseModel.h"
#import "CourseCell.h"
#import "UIImageView+WebCache.h"
#import "DetailViewController.h"
#import "SearchBarViewController.h"
#import "HistoryViewController.h"
#import "LoadCourseDataManager.h"

@interface CourseViewController ()

@end

@implementation CourseViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"课程分类";
        _sourceArray = [NSArray arrayWithObjects:@"全部来源", @"国内", @"国外",  @"TED", nil];
        _tagsArray = [NSArray arrayWithObjects:@"全部类型", @"文学", @"艺术",  @"哲学", @"历史", @"经济", @"社会",  @"法律", @"媒体", @"伦理", @"心理",  @"管理", @"技能", @"数学", @"物理", @"化学", @"生物", @"医学", @"环境",  @"计算机", nil];
        
        _showsArray = [[NSMutableArray alloc] init];
        LoadCourseDataManager *dataManger = [LoadCourseDataManager shareInstance];
        NSLog(@"-?????%d",dataManger.courseData.count);
        _showsArray = [dataManger.courseData mutableCopy];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshClicked) name:kTurnToMainViewNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self _initNavigationBarItem];
    [self _initPopoView];
    [self _initHeadView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CourseCell" bundle:nil] forCellReuseIdentifier:@"courseCell"];

}

- (void)_initHeadView
{
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 36)];
    greenView.backgroundColor = [UIColor colorWithRed:15/255.0 green:37/255.0 blue:16/255.0 alpha:1];
    [_headView addSubview:greenView];
    
    UIImageView *shadow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 36, 320, 4)];
    shadow.image = [UIImage imageNamed:@"shadow_down.png"];
    shadow.backgroundColor = [UIColor clearColor];
    [_headView addSubview:shadow];
    
    //按键
    _tagsButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_tagsButton setBackgroundImage:[UIImage imageNamed:@"filter_btn_active.png"] forState:UIControlStateNormal];
    _tagsButton.frame = CGRectMake(50, 5, 94, 26);
    [_tagsButton addTarget:self action:@selector(tagsButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:_tagsButton];
    
    _sourceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sourceButton setBackgroundImage:[UIImage imageNamed:@"filter_btn_active.png"] forState:UIControlStateNormal];
    _sourceButton.frame = CGRectMake(170, 5, 94, 26);
    [_sourceButton addTarget:self action:@selector(sourceButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:_sourceButton];
    
    //小箭头
    _tagsIconView = [[UIImageView alloc] initWithFrame:CGRectMake(123, 15, 11, 6)];
    _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
    [_headView addSubview:_tagsIconView];
    
    _sourceIcoView = [[UIImageView alloc] initWithFrame:CGRectMake(243, 15, 11, 6)];
    _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
    [_headView addSubview:_sourceIcoView];
    //标题
    _tagsLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 5, 65, 26)];
    _tagsLabel.font = [UIFont systemFontOfSize:13];
    _tagsLabel.backgroundColor = [UIColor clearColor];
    _tagsLabel.text = _tagsArray[0];
    _tagsLabel.textAlignment = NSTextAlignmentCenter;
    _tagsLabel.textColor = [UIColor whiteColor];
    [_headView addSubview:_tagsLabel];
    
    _sourceLabel = [[UILabel alloc] initWithFrame:CGRectMake(175, 5, 65, 26)];
    _sourceLabel.font = [UIFont systemFontOfSize:13];
    _sourceLabel.backgroundColor = [UIColor clearColor];
    _sourceLabel.text = _sourceArray[0];
    _sourceLabel.textAlignment = NSTextAlignmentCenter;
    _sourceLabel.textColor = [UIColor whiteColor];
    [_headView addSubview:_sourceLabel];
}

- (void)_initPopoView
{
    //类型分类布局
    _tagsView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 30, 303, 64)];
    UIImage *oldImage = [UIImage imageNamed:@"layout_bg1.png"];
    UIImage *newImage = [oldImage stretchableImageWithLeftCapWidth:25 topCapHeight:30];
    _tagsView.image = newImage;
    _tagsView.frame = CGRectMake(8, 30, 303, 184);
    _tagsView.userInteractionEnabled = YES;
    _tagsView.hidden = YES;
    
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            int temp = i*4+j;
            if (i == 0)
            {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitle:_tagsArray[temp] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:15];
                [button addTarget:self action:@selector(tagsViewButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = SourceButtonsTag+temp;
                if (j == 0)
                {
                    button.frame = CGRectMake(9, 20, 90, 30);
                    [button setTitleColor:[UIColor colorWithRed:31/255.0 green:62/255.0 blue:28/255.0 alpha:1] forState:UIControlStateNormal];
                    [button setBackgroundImage:[UIImage imageNamed:@"select_bg.png"] forState:UIControlStateNormal];
                    _preTagsButton = button;
                }
                else
                {
                    button.frame = CGRectMake(9+90+195/3*(j-1), 20, 195/3, 30);
                }
                [_tagsView addSubview:button];
            }
            else
            {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitle:_tagsArray[temp] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:15];
                [button addTarget:self action:@selector(tagsViewButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = SourceButtonsTag+temp;
                button.frame = CGRectMake(9+285/4*j, 20+30*i, 285/4, 30);
                [_tagsView addSubview:button];
            }

        }//for (int j = 0; j < 4; j++)
        
    }//for (int i = 0; i < 5; i++)

    
    [self.view addSubview:_tagsView];
    
    //来源按钮布局
    _sourceView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 30, 303, 64)];
    _sourceView.image = [UIImage imageNamed:@"layout_bg_iphone.png"];
    _sourceView.userInteractionEnabled = YES;
    _sourceView.hidden = YES;
    
    for (int i = 0; i < _sourceArray.count; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:_sourceArray[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button addTarget:self action:@selector(sourceViewButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = SourceButtonsTag+i;
        if (i == 0)
        {
            button.frame = CGRectMake(9, 20, 90, 30);
            [button setTitleColor:[UIColor colorWithRed:31/255.0 green:62/255.0 blue:28/255.0 alpha:1] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"select_bg.png"] forState:UIControlStateNormal];
            _preSourceButton = button;
        }
        else
        {
            button.frame = CGRectMake(9+90+195/3*(i-1), 20, 195/3, 30);
        }
        [_sourceView addSubview:button];
    }
    
    _popoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
    _popoView.backgroundColor = [UIColor clearColor];
    _popoView.hidden = YES;
    [_popoView addSubview:_tagsView];
    [_popoView addSubview:_sourceView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTap)];
    [_popoView addGestureRecognizer:tap];
    
    [self.view addSubview:_popoView];
}

- (void)tagsViewButtonClicked:(UIButton *)button
{
    self.noCourseView.hidden = YES;
    [_preTagsButton setBackgroundImage:nil forState:UIControlStateNormal];
    [_preTagsButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:31/255.0 green:62/255.0 blue:28/255.0 alpha:1] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"select_bg.png"] forState:UIControlStateNormal];
    _tagsLabel.text = button.titleLabel.text;
    _preTagsButton = button;
    [self reloadShowArray];
    
    _popoView.hidden = YES;
    
    _sourceView.hidden = YES;
    _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
    _tagsView.hidden = YES;
    _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
    _tableView.userInteractionEnabled = YES;

}

- (void)sourceViewButtonClicked:(UIButton *)button
{
    self.noCourseView.hidden = YES;
    [_preSourceButton setBackgroundImage:nil forState:UIControlStateNormal];
    [_preSourceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:31/255.0 green:62/255.0 blue:28/255.0 alpha:1] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"select_bg.png"] forState:UIControlStateNormal];
    _sourceLabel.text = button.titleLabel.text;
    _preSourceButton = button;
    [self reloadShowArray];
    
    _popoView.hidden = YES;
    
    _sourceView.hidden = YES;
    _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
    _tagsView.hidden = YES;
    _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
    _tableView.userInteractionEnabled = YES;
}

- (void)myTap
{
    if (_sourceView.hidden == NO || _tagsView.hidden == NO)
    {
        _popoView.hidden = YES;
        
        _sourceView.hidden = YES;
        _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
        _tagsView.hidden = YES;
        _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
        _tableView.userInteractionEnabled = YES;
    }
}

- (void)reloadShowArray
{
    LoadCourseDataManager *dataManger = [LoadCourseDataManager shareInstance];
    if (_showsArray != nil)
    {
        [_showsArray removeAllObjects];
        _showsArray = nil;
    }
    _showsArray = [[NSMutableArray alloc] init];
    if ([_tagsLabel.text isEqualToString:@"全部类型"] && [_sourceLabel.text isEqualToString:@"全部来源"])
    {
        _showsArray = [dataManger.courseData mutableCopy];
    }
    else if ([_tagsLabel.text isEqualToString:@"全部类型"] && ![_sourceLabel.text isEqualToString:@"全部来源"])
    {
        for (CourseModel *model in dataManger.courseData)
        {
            if ([model.source isEqualToString:_sourceLabel.text])
            {
                [_showsArray addObject:model];
            }
        }
    }//else if ([_tagsLabel.text isEqualToString:@"全部类型"])
    else if (![_tagsLabel.text isEqualToString:@"全部类型"] && [_sourceLabel.text isEqualToString:@"全部来源"])
    {
        for (CourseModel *model in dataManger.courseData)
        {
            NSRange range = [model.tags rangeOfString:_tagsLabel.text];
            if (range.location != NSNotFound)
            {
                [_showsArray addObject:model];
            }
        }
    }
    else
    {
        NSMutableArray *tempShowsArray = [[NSMutableArray alloc] init];
        for (CourseModel *model in dataManger.courseData)
        {
            if ([model.source isEqualToString:_sourceLabel.text])
            {
                [tempShowsArray addObject:model];
            }
        }//for (CourseModel *model in dele.courseData)
        for (CourseModel *model in tempShowsArray) {
            NSRange range = [model.tags rangeOfString:_tagsLabel.text];
            if (range.location != NSNotFound)
            {
                [_showsArray addObject:model];
            }
        }
    }
    if (_showsArray.count == 0)
    {
        self.noCourseView.hidden = NO;
    }
    
    [self.tableView reloadData];
}
#pragma mark --
#pragma mark NavigationBarItem

- (void)_initNavigationBarItem
{
    //搜索条
    UIButton *search = [UIButton buttonWithType:UIButtonTypeCustom];
    [search setImage:[UIImage imageNamed:@"search_ico.png"] forState:UIControlStateNormal];
    [search setImage:[UIImage imageNamed:@"search_ico_active.png"] forState:UIControlStateHighlighted];
    search.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:search];
    [search addTarget:self action:@selector(searchClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    //历史
    UIButton *history = [UIButton buttonWithType:UIButtonTypeCustom];
    [history setImage:[UIImage imageNamed:@"history_btn.png"] forState:UIControlStateNormal];
    [history setImage:[UIImage imageNamed:@"history_btn_active.png"] forState:UIControlStateHighlighted];
    history.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:history];
    [history addTarget:self action:@selector(historyClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void)historyClicked
{
    HistoryViewController *history = [[HistoryViewController alloc] init];
    
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
    [self.navigationController pushViewController:history animated:YES];
}

- (void)searchClicked
{
    SearchBarViewController *search = [[SearchBarViewController alloc] initWithNibName:@"SearchBarViewController" bundle:nil];
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    [self.navigationController pushViewController:search animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)sourceButtonClicked
{
    if (_sourceView.hidden && _tagsView.hidden)
    {
        _sourceView.hidden = NO;
        _popoView.hidden = NO;
        _sourceIcoView.image = [UIImage imageNamed:@"arrow1.png"];
        _tableView.userInteractionEnabled = NO;
    }
    else
    {
        _popoView.hidden = YES;
        
        _sourceView.hidden = YES;
        _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
        _tagsView.hidden = YES;
        _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
        _tableView.userInteractionEnabled = YES;

    }

}

- (void)tagsButtonClicked
{
    if (_sourceView.hidden && _tagsView.hidden)
    {
        _tagsView.hidden = NO;
        _popoView.hidden = NO;
        _tagsIconView.image = [UIImage imageNamed:@"arrow1.png"];
        _tableView.userInteractionEnabled = NO;

    }
    else
    {
        _popoView.hidden = YES;
        _sourceView.hidden = YES;
        _sourceIcoView.image = [UIImage imageNamed:@"arrow2.png"];
        _tagsView.hidden = YES;
        _tagsIconView.image = [UIImage imageNamed:@"arrow2.png"];
        _tableView.userInteractionEnabled = YES;

    }
}

#pragma mark --
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _showsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"courseCell"];
    
    CourseModel *model = [_showsArray objectAtIndex:indexPath.row];
    cell.titleLabel.text = model.title;
    cell.classLabel.text = model.tags;
    cell.playCountLabel.text = [NSString stringWithFormat:@"%@", model.playcount];
    cell.updatePlayCountLabel.text = [NSString stringWithFormat:@"%@", model.updatedPlaycount];
    [cell.courseImageView setImageWithURL:[NSURL URLWithString:model.imagePath]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 92;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    
    CourseModel *model = [_showsArray objectAtIndex:indexPath.row];
    detailController.videoCode = model.plid;
    
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
    [self.navigationController pushViewController:detailController animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

#pragma mark --
#pragma mark Notification
- (void)refreshClicked
{
    [self reloadShowArray];
}


#pragma mark --
#pragma mark viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    [UIView animateWithDuration:0.35 animations:^{
        view.frame = CGRectMake(0, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    }];
    [self reloadShowArray];
}

@end
